const express=require('express')
const bodyParser=require('body-parser')
const fs=require('fs')
var pool=require('./pool')
var app=express()
app.listen(8080)
app.use(express.static('public'))

app.use(bodyParser.urlencoded({
    extended:false
}))

app.post('/login',function(req,res){
    var obj=req.body
    console.log(obj);
    //连接数据库 执行sql语句
    pool.query('select * from userinfo where uname=? and upwd=?',[obj.uname,obj.upwd],function(err,result){
        if(err) throw err
        console.log(result.length)
        if(result.length>0){
        //    res.sendFile(__dirname+'/public/list.html')
        res.redirect('/list')
        }else{
            res.send('账号或者密码错误')
        }
    })
})

app.post('/regin',function(req,res){
    var obj=req.body
    console.log(obj);
    //连接数据库 执行sql语句
    pool.query('insert into userinfo set?',[obj],function(err,result){
        if(err) throw err
        console.log(result.affectedRows)
        if(result.affectedRows>0){
            res.sendFile(__dirname+'/public/login.html')
        }else{
            res.send('注册失败')
        }
      
    })
})

app.get('/list',function(req,res){
    pool.query('select * from userinfo',function(err,result){
        if(err) throw err
        console.log(result)
        if(result.length>0){
            for (var i=0;i<result.length;i++){
                var str=`<tr>
                <td>${result[i].uid}</td>
                <td>${result[i].uname}</td>
                <td>${result[i].upwd}</td>
                <td>
                <a href="">修改</a>
                &nbsp;
                <a href="location:8080/del?uid=${result[i].uid}">删除</a>
            </td>
            </tr>`
            }
            var strend=`</table>
            </body>
            </html>`
       
        fs.writeFileSync('./public/list.html', str+strend)
        res.sendFile(__dirname+('/public/list.html'))
        }else{
            res.send('数据为空')
        }
    })
})
//location:8080/del?uid=10
app.get('/del',function(req,res){
    var uid=req.query.uid
    pool.query('delete from userinfo where uid=?',[uid],function(err,result){
        if(err) throw err
        if(result.affectedRows>0){
             res.redirect('/list')
        }else(
            res.send('0')
        )
    })
})